'use strict'

import axios from 'axios'
import qs from 'qs'
import { Message, Loading, Toast } from 'element-ui'
import Router from '@/router/index'
// import store from '@/store/index'
// import router from "../../router";
// axios.defaults.baseURL = process.env.NODE_ENV === 'production' ? '' : '/request';

let loading;
//内存中正在请求的数量
let loadingNum = 0;
function startLoading() {
    if (loadingNum == 0) {
        loading = Loading.service({
            lock: true,
            text: '拼命加载中...',
            background: 'rgba(0,0,0,0.8)',
        })
    }
    //请求数量加1
    loadingNum++;
}
function endLoading() {
    //请求数量减1
    loadingNum--
    if (loadingNum <= 0) {
        loading.close()
    }
}

axios.defaults.timeout = 50000;
axios.defaults.response = 'json';
axios.defaults.withCredential = true;

axios.interceptors.request.use(
  config=>{
    startLoading()
        if (config.method === "post" && config.headers['Content-Type'] !== "multipart/form-data") {
            if (config.method === "post" && config.headers['Content-Type'] == "application/json") {
                config.data = config.data;
            } else {
                config.data = qs.stringify(config.data);
            }
        }

        config.timeout = config.headers['Content-Type'] === "multipart/form-data" ? '7200000' : '7200000'
        config.headers["session_id"] = window.sessionStorage.sessionId;
        return config;
  }
)

axios.interceptors.response.use(
  res=>{
    endLoading()
    if (res.status == 200) {
        if (res.data.type == 'application/vnd.ms-excel') {
            return res
        } else if (res.data.type == 'application/octet-stream') {
            return res;
        } else if (res.data.status == "SUCCESS") {
            return res;
        } else if (res.data.status == "REDIRECT") {
            window.open(res.data.result, "_self")
        } else if (res.data.status == "ERROR") {
            Message.error(res.data.errorMessage);
            return Promise.reject(res.data.errorMessage);
        }
    }
  },
  error=>{
    endLoading()
    if (error.response.status) {
        switch (error.response.status) {
            case 401:
                router.replace({
                    path: '/login',
                    query: {
                        redirect: router.currentRoute.fullPath
                    }
                });
                break;
            case 404:
                Message.error('网络请求不存在');
                break;
            default:
                Message.error(error.response.data.message);
        }
        let errorInfo = error;
        return Promise.reject(errorInfo);
    }
  }
)


export function post(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.post(url,data)
      .then(response => {
        if(response.status === 200){
          resolve(response);
        }else{
          Toast(reject.data.msg)
        }
      })
  })
}


